//
//  MainViewController.swift
//  Weibo
//
//  Created by 孙明海 on 16/1/23.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    //MARK: - 监听方法
    @objc private func clickComposedButton() {
        let vc: UIViewController
        
        if UserAccountViewModel.sharedUserAccount.userLogin {
            vc = ComposeViewController()
        } else {
            vc = OAuthViewController()
        }
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)
    }

    //MARK: - 视图生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()
        // 添加子控制器
        addChildViewControllers()
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 添加撰写按钮
        setupComposedButton()
    }

}

//MARK: - 设置界面
extension MainViewController {
    
    /// 设置撰写按钮
    private func setupComposedButton() {
        let btn = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
        
        let w = tabBar.bounds.width / CGFloat(childViewControllers.count) - 1
        btn.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        btn.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside) 
        
        tabBar.addSubview(btn)
    }
    /// 加载Tab bar 的子控制器
    private func addChildViewControllers() {
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    /// 加载控制器
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
}